package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.itheima.health.mapper.OrderMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.date.DateUtils;
import com.itheima.health.utils.pay.PayUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisMessageConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单添加：
 * - 订单表  会员表  预约表 三表业务更新
 * - 调用不同的服务，完成添加订单业务功能  @Reference  注解完成服务的调用
 */
@Service(loadbalance = "roundrobin", retries = 0)
@Transactional  // 本地事务
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Reference  //  调用 远程  服务
    private MemberService memberService;

    @Reference
    private OrderSettingService orderSettingService;

    @Override
    @LcnTransaction
    public Order add(Map map) {
    /*         try {
            Thread.sleep(110000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        //   重点
        String telephone = (String) map.get("telephone");
        String codeFromForm = (String) map.get("validateCode");
        String orderdate = (String) map.get("orderDate");
        String setmealId = (String) map.get("setmealId");
        Order order;
        // 1 .  验证码校验
        String codeFromRedis = (String) redisTemplate.opsForValue().get(RedisMessageConstant.SENDTYPE_ORDER + telephone);
        ;
        if (StringUtils.isBlank(codeFromRedis)) {
            throw new RuntimeException("验证码过期！");
        }
        if (!codeFromRedis.equals(codeFromForm)) {
            throw new RuntimeException("验证码错误");
        }
        //  2.  当天是否预约满   select count(1) from  t_ordersetting  where  number>reserviations and orderdate = ?
        int count = orderSettingService.isOrderOKorNot(orderdate);
        if (count <= 0) {
            throw new RuntimeException("当天预约满,择日再约！");
        }
        // 3 .  是否重复预约  -- 新会员还是老会员
        Member member = memberService.findMemberByTelephone(telephone);
        if (member != null) {
            //  老会员    根据member_id  setmealId   orderdate  判断是否重复预约
            //  select count(1) from t_order where  mid = ? and sid = ? and orderdate = ?
            int isNotExist = baseMapper.findOrderByMemberIDAndSetmealIDAndOrderDate(member.getId(), Integer.parseInt(setmealId), orderdate);
            if (isNotExist > 0) {
                throw new RuntimeException("请勿重复预约，择日预约");
            }
            // 预约 下单
            //  添加订单记录  +  预约表 已经预约数+1
            order = generateOrder(map, member);
        } else {
            member = new Member();
            member.setRegTime(new Date(System.currentTimeMillis()));
            member.setPhoneNumber(telephone);
            member.setSex((String) map.get("sex"));
            member.setName((String) map.get("name"));
            member.setIdCard((String) map.get("idCard"));
            // 新会员信息录入 t_member表中
            int mid = memberService.saveMember(member);  //  事务提交  主键才会诞生
            member.setId(mid);
            //  新会员  预约下单
            order = generateOrder(map, member);
        }
//        System.out.println(1/0);
        orderSettingService.updateReservationsByOrderDate(orderdate);  // update t_ordersetting set xxx=xxx+1  where  orderdate = ?
        return order;
    }

    @Override
    public Map findOrderInfoById(Long id) {
        return baseMapper.findOrderInfoById(id);
    }

    @LcnTransaction
    private Order generateOrder(Map map, Member member) {
        String orderType = (String) map.get("orderType");
        String orderdate = (String) map.get("orderDate");
        String setmealId = (String) map.get("setmealId");
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderStatus("未到诊");
        order.setOrderType(orderType);
        order.setOrderDate(DateUtils.parseString2Date(orderdate, "yyyy-MM-dd"));
        order.setSetmealId(Integer.parseInt(setmealId));
        order.setIsPay(0);
        order.setId(new Date().getTime());
        baseMapper.add(order);
        return order;
    }

    @Override
    public Map payById(Long id) {
        String priceStr = null;
        Float price = baseMapper.queryMealPriceByOid(id);
        priceStr = price.toString();
        String preString = priceStr.substring(0, priceStr.indexOf("."));
        String totalPay = preString + priceStr.substring(priceStr.indexOf(".") + 1, priceStr.length());
        String url = PayUtils.createOrder(id + "", totalPay);
        Map map = new HashMap();
        map.put("price", priceStr);
        map.put("url", url);
        return map;
    }

    @Override
    public Boolean checkOrderStatus(Long id) {
        return baseMapper.checkOrderStatus(id)!=null;
    }
}
